package com.cf.module.app;

import android.os.Build;
import android.webkit.WebSettings;

import com.cf.base.http.HttpManager;
import com.cf.base.http.bean.ErrorResponse;
import com.cf.base.http.converter.fastjson.FastJsonConverterFactory;
import com.cf.base.http.core.RetrofitService;
import com.cf.base.http.engine.impl.FastJsonEngine;
import com.cf.base.http.generator.BaseBodyErrorAdapter;
import com.cf.base.http.generator.impl.DefaultBodyErrorAdapter;
import com.cf.base.http.interceptor.headers.HeaderProvider;

import java.util.List;
import java.util.Map;

import okhttp3.Headers;
import okhttp3.OkHttpClient;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

public class HttpConfig {

    public static final String HTTP_MODULE_USER = "USER";
    public static final String HTTP_MODULE_USER_URL = "http://127.0.0.1:8080";

    private static HeaderProvider headerProvider = new HeaderProvider() {
        @Override
        public Headers defaultHeaders() {
            Headers.Builder builder = new Headers.Builder().add("User-Agent", getUserAgent());
            return builder.build();
        }

        @Override
        public String[] getHeaderKey() {
            return new String[]{};
        }

        @Override
        public Map<String, String> getHeaderByKey(List<String> list) {

            return null;
        }
    };

    private static String getUserAgent() {
        String userAgent = "";
        try {
            userAgent = WebSettings.getDefaultUserAgent(MyApplication.getContext());
        } catch (Exception e) {
            userAgent = System.getProperty("http.agent");
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0, length = userAgent != null ? userAgent.length() : 0; i < length; i++) {
            char c = userAgent.charAt(i);
            if (c <= '\u001f' || c >= '\u007f') {
                sb.append(String.format("\\u%04x", (int) c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    public static void init() {
        HttpManager.getInstance().registerProvider(HTTP_MODULE_USER, s ->
                RetrofitService
                        .RetrofitBeanBuilder
                        .create()
                        .moduleName(HTTP_MODULE_USER)
                        .baseUrl(HTTP_MODULE_USER_URL)
                        .client(new OkHttpClient.Builder())
                        .header(headerProvider)
                        .retrofitFactory(FastJsonConverterFactory.create(), RxJava2CallAdapterFactory.create())
                        .errorAdapter(new DefaultBodyErrorAdapter<ErrorResponse>(FastJsonEngine.create()) {
                        })
                        .build()
        );
    }

}
